package com.xjoyt.pay.master.dao.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.master.dao.DistributorPassportRepositoryCustom;
import com.xjoyt.pay.master.po.Distributor;
import com.xjoyt.pay.master.po.DistributorPassport;
import com.xjoyt.pay.master.repository.DistributorPassportRepository;
import com.xjoyt.pay.master.security.PassportSecurity;
import com.xjoyt.pay.master.security.PassportHex;

public class DistributorPassportRepositoryImpl extends AbstractDao implements DistributorPassportRepositoryCustom {

	@Autowired
	private DistributorPassportRepository repository;

	@Autowired
	private PassportSecurity passportSecurity;

	@Override
	public ExecuteResult<?> save(Distributor distributor, String password) {
		repository.findAllByDistributorIdAndEnabled(distributor.id).forEach(item -> {
			item.enabled = false;
			repository.save(item);
		});
		DistributorPassport entity = new DistributorPassport();
		entity.addedDate = new Date();
		entity.enabled = true;
		entity.distributor = distributor;

		PassportHex hex = passportSecurity.createHex(password);
		entity.type = hex.type;
		entity.key = hex.key;
		entity.password = hex.password;
		repository.save(entity);

		return ExecuteResult.ok();
	}

	@Override
	public DistributorPassport findOneByDistributorIdAndEnabled(String distributorId) {
		Page<DistributorPassport> page = repository.findAllByDistributorIdAndEnabled(distributorId, getFirstPageable());
		return page.hasContent() ? page.iterator().next() : null;
	}

}
